<template>
  <div class="group-buy-detail-container">
      <el-card title="团购详情">
        <!-- 基本信息区域 -->
        <div class="basic-info">
          <el-descriptions :column="1" border>
            <el-descriptions-item label="团购编号">{{ groupBuyDetail.id }}</el-descriptions-item>
            <el-descriptions-item label="商户编号">{{ groupBuyDetail.merchantId }}</el-descriptions-item>
            <el-descriptions-item label="团购名称">{{ groupBuyDetail.name }}</el-descriptions-item>
            <el-descriptions-item label="团购描述">
              <span class="description-content">{{ groupBuyDetail.description }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="折扣价格">
              <span class="price discount-price">¥{{ formatPrice(groupBuyDetail.discount) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="原价">
              <span class="price original-price">¥{{ formatPrice(groupBuyDetail.price) }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="团购限制人数">{{ groupBuyDetail.personNum }}人/单</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 商品列表区域 -->
        <div class="goods-list-section">
          <h3 class="section-title">包含商品列表</h3>
          <el-table
              border
              stripe
              style="width: 100%; margin-top: 10px"
              :data="groupBuyDetail.goodsList || []"
          >
            <el-table-column prop="id" label="商品ID" width="120" align="center"></el-table-column>
            <el-table-column prop="name" label="商品名称" align="center"></el-table-column>
            <el-table-column prop="num" label="数量" width="100" align="center"></el-table-column>
            <el-table-column prop="price" label="单价" width="120" align="center">
              <template #default="scope">¥{{ formatPrice(scope.row.price) }}</template>
            </el-table-column>
            <el-table-column label="小计" width="120" align="center">
              <template #default="scope">
                ¥{{ formatPrice(scope.row.price * scope.row.num) }}
              </template>
            </el-table-column>
          </el-table>



          <!-- 商品总计 -->
          <div class="goods-total" v-if="groupBuyDetail.goodsList && groupBuyDetail.goodsList.length">
            <span>商品总价：</span>
            <span class="total-price">
              ¥{{ formatPrice(calculateTotalGoodsPrice()) }}
            </span>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button @click="handleBack">返回列表</el-button>
          <el-button type="primary" @click="handleEdit">编辑</el-button>
        </div>
      </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import server from "../utils/request.js";

// 路由相关
const route = useRoute();
const router = useRouter();

const groupBuyDetail = ref({
  id: '',
  merchantId: '',
  name: '',
  description: '',
  totalCount: 0,
  discount: 0,
  price: 0,
  personNum: 0,
  goodsList: [] // 商品列表
});

// 页面挂载时加载详情数据
onMounted(() => {
  fetchGroupBuyDetail();
});

// 获取团购详情（修正API请求逻辑）
const fetchGroupBuyDetail = async () => {
  try {
    // 从路由参数中获取团购ID
    const { id } = route.query; // 确保路由参数正确传递
    if (!id) {
      ElMessage.error('缺少团购ID参数');
      return;
    }
    const { data:data } = await server.post(`groupBuy/${id}`);
    if (data.code === 200) {
      Object.assign(groupBuyDetail.value,data.data[0])
      console.log(groupBuyDetail.value)
    } else {
      ElMessage.error(data.msg || '获取详情失败');
    }
  } catch (error) {
    console.error('请求错误:', error);
    ElMessage.error('网络错误，加载详情失败');
  } finally {
    // 无论成功失败都关闭加载
  }
};

// 格式化价格（保留两位小数，兼容null/undefined）
const formatPrice = (price) => {
  if (!price && price !== 0) return '0.00';
  return Number(price).toFixed(2);
};

// 计算商品总价（增加空值判断）
const calculateTotalGoodsPrice = () => {
  if (!groupBuyDetail.value.goodsList || !groupBuyDetail.value.goodsList.length) {
    return 0;
  }
  return groupBuyDetail.value.goodsList.reduce((total, item) => {
    const itemPrice = Number(item.price) || 0;
    const itemNum = Number(item.num) || 0;
    return total + itemPrice * itemNum;
  }, 0);
};

// 返回列表页
const handleBack = () => {
  router.push('/groupBuyList'); // 根据实际路由调整
};

// 编辑团购
const handleEdit = () => {
  router.push({
    path: '/group-buy-edit',
    query: { id: groupBuyDetail.value.id } // 统一使用query参数，与详情页保持一致
  });
};
</script>

<style scoped>
/* 原有样式保持不变 */
.group-buy-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

/* 新增无商品提示样式 */
.no-goods {
  text-align: center;
  padding: 30px;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 4px;
}

/* 其他样式... */
.basic-info {
  margin-bottom: 30px;
}

.description-content {
  white-space: pre-wrap;
  line-height: 1.6;
}

.price {
  font-weight: 500;
}

.discount-price {
  color: #ff4d4f;
}

.original-price {
  color: #666;
  text-decoration: line-through;
  margin-left: 10px;
}

.goods-list-section {
  margin: 30px 0;
}

.section-title {
  font-size: 16px;
  color: #1f2329;
  margin-bottom: 10px;
  font-weight: 500;
}

.goods-total {
  text-align: right;
  margin-top: 15px;
  font-size: 15px;
}

.total-price {
  color: #ff4d4f;
  font-weight: bold;
  font-size: 16px;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>